<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\Notice as NoticeModel;
use addons\kuerp\model\NoticeRead;

/**
 * 公告接口
 */
class Notice extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//公告列表
	public function getList() {
		$limit = input("limit/d", 10);


		$authid=$this->auth->id;
		$records = NoticeModel::where([
		])->where(function ($query) use ($authid) {
			$query->where('owner_admin_ids', 'like', "%,$authid,%")->whereOr('owner_admin_ids', 'eq', "");
		})->order('id desc')->paginate($limit);

		$items   = $records->items();
		foreach ($items as $k => $v) {
			$read_admin_ids = explode(',', $v['read_admin_ids']);
			$v['is_read']   = in_array($this->auth->id, $read_admin_ids)? 1: 0;
			$items[$k]      = $v;
		}
		$this->success('请求成功', $records);
	}


	//获取公告详情
	public function getDetail() {
		$id     = input('id', '', 'intval');
		$notice = NoticeModel::where(['id' => $id])->find();
		if (empty($notice)) {
			$this->error('公告不存在');
		}
		$read_admin_ids = explode(',', $notice['read_admin_ids']);
		if (!in_array($this->auth->id, $read_admin_ids)) {
			$read_admin_ids[] = $this->auth->id;
			NoticeModel::where(['id' => $notice['id']])->update(['read_admin_ids' => implode(',', $read_admin_ids).',']);

		}
        if(!NoticeRead::where(['notice_id'=>$id,'admin_id'=>$this->auth->id])->find()){
            //添加阅读记录
            NoticeRead::addRead($id, $this->auth->id);
        }
        preg_match_all('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$notice['content'],$match);
        foreach ($match[1] as $v){
            $notice['content']=str_replace($v,cdnurl($v,true),$notice['content']);
        }
		$notice['is_edit']   = ($this->auth->id == $notice['create_admin_id']) ? 1 : 0;

		$this->success('请求成功', $notice);
	}

	//添加通告
	public function addNotice() {
		$params                    = $this->request->post();
		$params['owner_staff_ids'] = ',' . $params['owner_staff_ids'] . ',' . $this->auth->id . ',';
		$params['create_staff_id'] = $this->auth->id;
		$result                    = (new NoticeModel())->save($params);
		if (!$result) {
			$this->error('提交失败');
		}
		$this->success('提交成功');
	}

	//修改公告
	public function editNotice(){
		$params                    = $this->request->post();
		if(empty($params['id'])){
			$this->error('参数错误');
		}
		$result                    = (new NoticeModel())->save($params,['id'=>$params['id']]);
		if (!$result) {
			$this->error('提交失败');
		}
		$this->success('提交成功');
	}


}
